//设备定位控制器
app.controller('sos_sign',["$scope","async","baidu",function($scope,msg,baidu) {
    $scope.model = msg.init.model;
    $scope.address = msg.init.address;
    $scope.time = msg.init.sosTime;
    $scope.point = msg.init.point;
    $scope.src = msg.init.src;

    var t = setInterval(function() {
        if(window.BMap && window.BMap.Map) {
            var map = new BMap.Map("allMap");            // 创建Map实例
            var point = new BMap.Point($scope.point[0], $scope.point[1]); // 创建点坐标
            map.centerAndZoom(point,18);
            // 添加左上角控件
            map.addControl(new BMap.NavigationControl());
            //启用滚轮放大缩小               
            map.enableScrollWheelZoom();

            var marker = new BMap.Marker(point);
            var circle = new BMap.Circle(point,50,{strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});

            // 将标注添加到地图中
            map.addOverlay(marker);
            map.addOverlay(circle);
            marker.setAnimation(BMAP_ANIMATION_BOUNCE)             

            // 注册地图的一个点击事件
            map.addEventListener("click", function(e){
                console.log(e.point.lng + ", " + e.point.lat);
            });
            clearInterval(t);
        }
    }, 400);

    $scope.back = function() {
        window.history.back(-1)
    }
}])

// 设备报警记录列表
app.controller('sos_list',["$scope","async",function($scope,msg) {
    $scope.myUrl = urlAddress;
    
    //将获取的数据跟传给控制器
    $scope.opints = msg;
      $scope.number = $scope.opints.length;
    if ($scope.opints.length < 1) {
         $scope.hasSign = true;
    } else {
         $scope.hasSign = false;
    }

      //删除用户
    $scope.delUser = function() {
        // 获取所有被选中的元素及其对应的用户ID
        var delID = [];
        $("table td input").each(function() {
           if ($(this).prop("checked")) {
              delID.push($(this).parents("tr").attr("userID"));
           };
        })
         if(delID.length == 0) {
           alert("你没有选择任何设备");
         } else {
          console.log(delID);
            // window.location.reload();
         }
    }

    // 全选效果以及反选
    allChecked();

    $scope.back = function() {
        window.history.back(-1);
    }   
}])

//设置行动区域
app.controller('safe_map',["$scope","async","baidu","$routeParams",function($scope,msg,baidu,$routeParams) {
    // 判断是不是新建的
    if ($routeParams.id == "new") {
        $scope.initData = {}
    } else {
        var n = parseInt($routeParams.id);
        $scope.initData = msg.file[n];
    }

    $scope.model = $scope.initData.model || "安全区";
    $scope.point = $scope.initData.point || null;
    $scope.address = $scope.initData.address || "请点击按钮在地图上选择一个点";
    $scope.name = $scope.initData.name || null;
    $scope.range = $scope.initData.r * 10 || 30;

    $scope.ckAddr = function() {
        $scope.api.clearR();
        $scope.isAddFile = true;
    }

    $scope.api = {};
    $scope.api.changeR = function() {};
    $scope.api.clearR = function() {};

    var t = setInterval(function() {
        if(window.BMap && window.BMap.Map) {
            // 创建Map实例
            var map = new BMap.Map("allMap");
            // 地址解析器
            var geoc = new BMap.Geocoder();

            //启用滚轮放大缩小
            map.enableScrollWheelZoom();
             // 添加左上角控件
            map.addControl(new BMap.NavigationControl());

            // 判断是不是新建的，如果不是则添加
            var point,marker,circle;
            if($scope.point)  {
                // 创建点坐标
                point = new BMap.Point($scope.point[0], $scope.point[1]); 
                map.centerAndZoom(point,17); 
                addMarker(point);
                
                $scope.api.changeR = function(r) {
                    circle.setRadius(r);
                }              
            } else {
                var geolocation = new BMap.Geolocation();
                geolocation.getCurrentPosition(function(r){
                    if(this.getStatus() == BMAP_STATUS_SUCCESS){
                       point = new BMap.Point(r.point.lng,r.point.lat);
                    } else {
                        point = new BMap.Point(116.331398,39.897445);
                    };
                    map.centerAndZoom(point,13);      
                },{enableHighAccuracy: true})
            }

            // 注册地图的一个点击事件
            map.addEventListener("click", function(e){
                if($scope.isAddFile) {
                    map.setZoom(17);
                    $scope.isAddFile = false;
                    point = new BMap.Point(e.point.lng, e.point.lat);
                    addMarker(point);
                    map.panTo(point);
                    getAddress(point);

                    $scope.api.changeR = function(r) {
                        circle.setRadius(r);
                    } 
                }
            });
             
             // 清除覆盖物 
            $scope.api.clearR = function() {
                map.removeOverlay(marker);
                map.removeOverlay(circle);  
            }

            // 添加覆盖物
            function addMarker(point) {
                marker = new BMap.Marker(point);
                circle = new BMap.Circle(point,$scope.range * 10,{strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
                
                map.addOverlay(marker);
                map.addOverlay(circle);
                marker.setAnimation(BMAP_ANIMATION_BOUNCE);  
            }

            //利用坐标点获取地址
            function getAddress(pt) {
                geoc.getLocation(pt, function(rs){
                    var addComp = rs.addressComponents;
                    var addrStr = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                    $scope.address = addrStr + "附近";
                    $scope.$apply()
                    console.log(addrStr);
                });  
            }

            clearInterval(t);
        }
    },300);

    $scope.rangeChange = function() {
        $scope.r = function() {
            $scope.range = limitValue($scope.range,50,10);
            return $scope.range / 10
        }();
        $scope.api.changeR($scope.range * 10);
    };
    $scope.rangeChange();
    
    $scope.save = function($event) {
        console.log($event);
    }

    $scope.back = function() {
        window.history.back(-1);
    }
}])

//查看行动区域列表
app.controller('safe_file',["$scope","async",function($scope,msg) {
    $scope.myUrl = urlAddress;

    $scope.options = msg.file;

    $scope.del = function($event) {
        console.log($event);
    }

    $scope.back = function() {
        window.history.back(-1)
    }
}])

//移动轨迹图
app.controller('move_record',["$scope","async","baidu",function($scope,msg,baidu) {
    $scope.model = msg.init.model;
    $scope.address = msg.init.address;
    $scope.lasttime = msg.init.lasttime;
    $scope.point = msg.init.point;
    $scope.move = msg.move;
    $scope.checkedTime = 50;

    // 调节时间
    $scope.range = function($event) {
        $scope.ckTime = function() {
            var n = parseInt($scope.checkedTime * 24 * 60 / 100);
            var hour = parseInt(n / 60);
            var min = n % 60;
            var time = beforeZero(hour) + ":" + beforeZero(min);
            console.log(time);
            return time 
        }();
    }
    $scope.range();

    //折线模拟路线
    var t = setInterval(function() {
        if(window.BMap && window.BMap.Map) {
            var map = new BMap.Map("allMap");            // 创建Map实例
            var point = new BMap.Point($scope.point[0], $scope.point[1]); // 创建点坐标
            var bounds = [];
            var linesPoints = [];
            map.centerAndZoom(point,18);                 
            map.enableScrollWheelZoom();//启用滚轮放大缩小
             // 添加左上角控件
            map.addControl(new BMap.NavigationControl());

            var points1 = [];
            function addMarker(point,n){
               var marker = new BMap.Marker(point);
               map.addOverlay(marker);

               var label = new BMap.Label(1 + n + "",{offset:new BMap.Size(0,2)});
                label.setStyle({
                    background : "none",
                    color: "#fff",
                    fontSize: "12px",
                    lineHeight: "16px",
                    width : "16px",
                    height: "16px",
                    border: "none",
                    textAlign: "center"
                })
                marker.setLabel(label);
            }
            for (var i = 0; i < $scope.move[0].length; i++) {
                var point = new BMap.Point($scope.move[0][i][0], $scope.move[0][i][1]);
                addMarker(point,i)
                points1.push(point);
            };

            // 创建一条折线
            var polyline = new BMap.Polyline(points1,{strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5})
            map.addOverlay(polyline);

            clearInterval(t);
        }
    },300);

    // GPS导航模拟路线
    // var t = setInterval(function() {
    //      if(window.BMap && window.BMap.Map) {
    //             console.log($scope.point);
    //             var map = new BMap.Map("allMap");            // 创建Map实例
    //             var point = new BMap.Point($scope.point[0], $scope.point[1]); // 创建点坐标
    //             var bounds = [];
    //             var linesPoints = [];
    //             map.centerAndZoom(point,18);                 
    //             map.enableScrollWheelZoom();//启用滚轮放大缩小
    //              // 添加左上角控件
    //             map.addControl(new BMap.NavigationControl());

    //             var points1 = [];
    //             for (var i = 0; i < $scope.move[0].length; i++) {
    //                 points1.push(new BMap.Point($scope.move[0][i][0], $scope.move[0][i][1]));
    //             };

    //             console.log(points1);
    //             // 驾车实例,并设置回调
    //             var driving3 = new BMap.DrivingRoute(map,{onSearchComplete:drawLine});
    //             driving3.search(points1[0], points1[points1.length-1],{
    //                 startCity: "厦门",
    //                 endCity: "厦门",
    //                 waypoints: points1
    //             }); 

    //             function drawLine(results){
    //                 console.log(results);
    //                 var opacity = 0.45;
    //                 var planObj = results.getPlan(0);
    //                 var b = new Array();
    //                 var addMarkerFun = function(point,imgType,index,title) {
    //                     var url;
    //                     var width;
    //                     var height;
    //                     var myIcon;
    //                     // imgType:1的场合，为起点和终点的图；2的场合为车的图形
    //                     if(imgType == 1){
    //                         url = "http://developer.baidu.com/map/jsdemo/img/dest_markers.png";
    //                         width = 42;
    //                         height = 34;
    //                         myIcon = new BMap.Icon(url,new BMap.Size(width, height),{offset: new BMap.Size(14, 32),imageOffset: new BMap.Size(0, 0 - index * height)});
    //                     } else {
    //                         url = "http://developer.baidu.com/map/jsdemo/img/trans_icons.png";
    //                         width = 22;
    //                         height = 25;
    //                         var d = 25;
    //                         var cha = 0;
    //                         var jia = 0;
    //                         if(index == 2){
    //                             d = 21;
    //                             cha = 5;
    //                             jia = 1;
    //                         }
    //                         myIcon = new BMap.Icon(url,new BMap.Size(width, d),{offset: new BMap.Size(10, (11 + jia)),imageOffset: new BMap.Size(0, 0 - index * height - cha)});
    //                     }
                    
    //                     var marker = new BMap.Marker(point, {icon: myIcon});
    //                     if(title != null && title != "") {
    //                         marker.setTitle(title);
    //                     }
    //                     // 起点和终点放在最上面
    //                     if(imgType == 1){
    //                         marker.setTop(true);
    //                     }
    //                     map.addOverlay(marker);
    //                 }
    //                 var addPoints = function(points) {
    //                     for(var i = 0; i < points.length; i++){
    //                         bounds.push(points[i]);
    //                         b.push(points[i]);
    //                     }
    //                 }   
    //                 // 绘制驾车步行线路
    //                 for (var i = 0; i < planObj.getNumRoutes(); i ++){
    //                     var route = planObj.getRoute(i);
    //                     if (route.getDistance(false) <= 0){continue;}
    //                     addPoints(route.getPath());
    //                     // 驾车线路
    //                     if(route.getRouteType() == BMAP_ROUTE_TYPE_DRIVING){
    //                         map.addOverlay(new BMap.Polyline(route.getPath(), {strokeColor: "#0030ff",strokeOpacity:opacity,strokeWeight:6,enableMassClear:true}));
    //                     }else{
    //                     // 步行线路有可能为0
    //                         map.addOverlay(new BMap.Polyline(route.getPath(), {strokeColor: "#30a208",strokeOpacity:0.75,strokeWeight:4,enableMassClear:true}));
    //                     }
    //                 }   
    //                 map.setViewport(bounds);    
    //                 // 终点  
    //                 addMarkerFun(results.getEnd().point,1,1);
    //                 // 开始点
    //                 addMarkerFun(results.getStart().point,1,0);
    //                 linesPoints[linesPoints.length] = b;
    //             }


    //             function showInfo(e){
    //                console.log(e.point.lng + ", " + e.point.lat);
    //             }
    //             map.addEventListener("click", showInfo);
    //             clearInterval(t);
    //         }
    // }, 300);

    $scope.back = function() {
        window.history.back(-1)
    }

    // 日期相关模块
    $scope.getNewData = function(da) {
        console.log(da.year + "年" + da.month + "月");
        $(".now_day").html(da.year + "年" + da.month + "月" + da.date + "日");
        $scope.data = da;
    }

    //创建日期组件
    $scope.dataFn = new dataFn();
    $scope.dataFn.creat($("#data"),$scope.getNewData);

    $scope.prvDay = function() {
    $scope.data.date -= 1;
    if ($scope.data.date <= 0) {
      $scope.data.month -= 1
      if(month <= 0) {
         $scope.data.month = 12;
         $scope.data.year -= 1
      }
      $scope.data.date = $scope.dataFn.getMaxDay($scope.data.month,$scope.data.year);
    }
    $scope.dataFn.init($("#data"),$scope.data);
    $scope.getNewData($scope.data);
    }

    $scope.nowDay = function() {
        if ($scope.dataShow) {
          $scope.dataShow = false;
        } else {
          $scope.dataShow = true;
        }
    }
    $scope.nextDay = function() {
        var maxDays = $scope.dataFn.getMaxDay($scope.data.month,$scope.data.year);
        $scope.data.date += 1;
        if ($scope.data.date > maxDays) {
            $scope.data.date = 1;
            $scope.data.month += 1
            if(month > 12) {
               $scope.data.month = 1;
               $scope.data.year += 1
            }
        }
        $scope.dataFn.init($("#data"),$scope.data);
        $scope.getNewData($scope.data);
    }
}])

//设备定位控制器
app.controller('dev_position',["$scope","async","baidu",function($scope,msg,baidu) {
    $scope.model = msg.init.model;
    $scope.address = msg.init.address;
    $scope.lasttime = msg.init.lasttime;
    $scope.point = msg.init.point;

    var t = setInterval(function() {
        if(window.BMap && window.BMap.Map) {
            var map = new BMap.Map("allMap");            // 创建Map实例
            var point = new BMap.Point($scope.point[0], $scope.point[1]); // 创建点坐标
            map.centerAndZoom(point,18);
            // 添加左上角控件
            map.addControl(new BMap.NavigationControl());
            //启用滚轮放大缩小               
            map.enableScrollWheelZoom();

            var marker = new BMap.Marker(point);
            var circle = new BMap.Circle(point,50,{strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});

            // 将标注添加到地图中
            map.addOverlay(marker);
            map.addOverlay(circle);
            marker.setAnimation(BMAP_ANIMATION_BOUNCE)             

            // 注册地图的一个点击事件
            map.addEventListener("click", function(e){
                console.log(e.point.lng + ", " + e.point.lat);
            });
            clearInterval(t);
        }
    }, 400);

    $scope.back = function() {
        window.history.back(-1)
    }
}])

//设备信息设置控制器
app.controller('dev_set',["$scope","async",function($scope,async){
	$scope.vol = 20;
	$scope.myUrl = urlAddress;
	function initVol(n) {
		var w = parseInt(($(".linebox").width() - 12) * n / 100);
		$(".blueline").width(w);
	}
	initVol($scope.vol);

    $scope.changVol = function($event) {
    	var w = $event.offsetX + 6;
    	if(w < 12) {
    		w = 12;
    	} 
    	if(w > 270) {
    		w = 270
    	}
    	$(".blueline").width(w);
    	var full = $(".linebox").width() - 12;
    	$scope.vol = parseInt((w - 12)*100 / full);
    }
}])

//用户信息管理详情页控制器
app.controller("us_det",["$scope","async",function($scope,msg){
    //初始化数据
    $scope.init = msg.init;
    $scope.initFn = function(data) {
        $scope.name = data.name;
        $scope.account = data.account;
        $scope.sex = data.sex;
        if($scope.sex == "男") {
            $(".sex label").eq(0).addClass("checked").siblings("label").removeClass("checked");
        } else {
            $(".sex label").eq(1).addClass("checked").siblings("label").removeClass("checked");
        }
        $scope.password = data.password;
        $scope.address = data.address;
        $scope.name2 = data.name2;
        $scope.startTime = data.startTime;
        $scope.lastTime = data.lastTime;
    }
    $scope.initFn($scope.init);

    //控制是否修改信息
    $scope.changeform = true;
    $scope.save = function() {
        $scope.changeform = true;
       $(".sex").addClass("disabled");
    }
    $scope.exit = function() {
          $scope.changeform = true;
         $(".sex").addClass("disabled");
         $scope.initFn(msg.init);
    }
    $scope.write = function() {
        $scope.changeform = false;
        $(".sex").removeClass("disabled");
    }
    // 性别造假控制函数
    $scope.checkSex = function($event) {
        var _this = $event.target
        $(_this).parent().addClass("checked").siblings("label").removeClass("checked");
    }

    // 表单验证显示函数 
    $scope.nameblur = function(bool) {
       $scope.nameblur1 = bool;
    }
    $scope.passwordblur = function(bool) {
       $scope.passwordblur1 = bool;
    }
    $scope.addressblur = function(bool) {
       $scope.addressblur1 = bool;
    }
    $scope.name2blur = function(bool) {
       $scope.name2blur1 = bool;
    }

    $scope.opints = msg.data;

    // 全选效果以及反选
    allChecked()
}]);
